package com.nervenets.web.controller.handler.admin.news;

import com.nervenets.utils.StringUtils;
import com.nervenets.web.controller.handler.SessionHandler;
import com.nervenets.web.enumeration.Role;
import com.nervenets.web.hibernate.domain.news.News;
import lombok.Data;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class NewsForManagerHandler extends SessionHandler<NewsForManagerParams> {
    @Override
    public ArrayList<Role> allowRoles() {
        return Role.administrator();
    }

    @Override
    public boolean needLog() {
        return false;
    }

    @Override
    public String handle(NewsForManagerParams params, HttpServletRequest request) throws Exception {
        String hql = "from News where removed = 0 and type = ? ";
        List<Object> objects = new ArrayList<>();
        objects.add(params.getNewsType());

        if (params.getTagId() > 0) {
            hql += "and tagId = ? ";
            objects.add(params.getTagId());
        }

        if (!StringUtils.isEmpty(params.getKeyword())) {
            hql += "and title like ? or content like ? ";
            objects.add("%" + params.getKeyword() + "%");
            objects.add("%" + params.getKeyword() + "%");
        }
        BigDecimal countOfByHql = userDao.getCountOfByHql(hql, objects);

        hql += "order by id desc ";

        List<News> news = userDao.getAllObjectsByHql(hql, objects, params.getStart(), params.getLimit());
        List<NewsModel> models = new ArrayList<>();
        for (News ne : news) {
            models.add(new NewsModel(ne));
        }
        return successMessage(models,
                new KeyValue("start", params.getStart()),
                new KeyValue("total", countOfByHql.intValue()));
    }

    @Override
    public String result() throws Exception {
        return successMessage("资讯列表");
    }

    @Data
    public class NewsModel implements Serializable {
        private long newsId;
        private int createTime;
        private String title;
        private String bigCoverImage;
        private String smallCoverImage;
        private int queue;
        private boolean hot;

        public NewsModel(News news) {
            this.newsId = news.getId();
            this.createTime = news.getCreateTime();
            this.title = news.getInfo().getTitle();
            this.bigCoverImage = news.getInfo().getBigCoverImage();
            this.smallCoverImage = news.getInfo().getSmallCoverImage();
            this.queue = news.getQueue();
            this.hot = news.isHot();
        }
    }
}
